<?php

namespace App\Services\User;

use App\CodeResponse;
use App\Exceptions\BusinessException;
use App\Models\User\Address;
use App\Services\BaseServices;
use Illuminate\Database\Eloquent\Collection;

class AddressServices extends BaseServices
{
    /**
     * 获取地址列表
     * @param  int  $userId
     * @return Address[]|Collection
     */
    public function getAddressListByUserId(int $userId)
    {
        return Address::query()->where(['user_id' => $userId], ['deleted' => 0])->get();
    }

    /**
     * 获取用户地址
     * @param $userId
     * @param $addressId
     * @return Address|\Illuminate\Database\Eloquent\Model|null
     */
    public function getAddress($userId, $addressId)
    {
        return Address::query()->where('user_id', $userId)->where('id', $addressId)->where('deleted', 0)->first();
    }

    public function getUserAddress($id)
    {
        return Address::query()->where(['id' => $id], ['deleted' => 0])->first();
    }

    /**
     * 删除用户地址
     * @param $userId
     * @param $addressId
     * @return bool|null
     * @throws BusinessException
     */
    public function delete($userId, $addressId)
    {
        $address = $this->getAddress($userId, $addressId);
        if (is_null($address)) {
            $this->throwBusinessException(CodeResponse::PARAM_ILLEGAL);
        }
        return $address->delete();
    }

}
